//
//  HMQauthViewController.swift
//  WymanWeibo
//
//  Created by wyman on 16/4/9.
//  Copyright © 2016年 wyman. All rights reserved.
//

import UIKit

import SVProgressHUD

class HMQauthViewController: UIViewController {

    /**
     loadview赋值不用关心view的大小
     */
    override func loadView() {
    view = webView
        
        webView.delegate = self
     
 
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置背景颜色
        self.view.backgroundColor = HMGlobalColor
        self.setupNavitationBar()
        
        
        let url = oatuthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        
        SVProgressHUD.showWithStatus("努力加载中...")
        
        SVProgressHUD.setDefaultMaskType(.None)
       
    }
   
    private func oatuthURL() -> NSURL{
    
        let urlString = OauthUrl + "?client_id="+client_id + "&redirect_uri=" + redirect_uri
    
    return NSURL(string: urlString)!
    }
    
    
    func setupNavitationBar(){
    //添加左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: .Plain, target: self, action: Selector("autofill"))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: Selector("close"))
    
    
    }
    
    //MARK: - 实现事件
     @objc private func autofill(){
    
        let js = "document.getElementById('userId').value = 'wu5351513@126.com';document.getElementById('passwd').value = 'wuyan5351513'"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
    
    }
    
     @objc private func close(){
        
        self.dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
        
    }
    
    //MARK: - 懒加载
    private lazy var webView: UIWebView = UIWebView()
}


extension HMQauthViewController:UIWebViewDelegate{
    
    
    
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urString = request.URL?.absoluteString
//        HMPrint(urString)
        // http://www.douyu.com/?code=41ee758545c911b3f5b17785f40c1790
        
        //http://www.douyu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_denied&error_description=user%20denied%20your%20request.&error_code=21330
        
        //判断是否是授权回调地址
        let isRedrectURL = urString!.hasPrefix(redirect_uri)
        if !isRedrectURL {
            return true
        }else{
        
            let codeString = "code="
            let quey = request.URL?.query
            
            
            if quey!.hasPrefix(codeString) {
                
            let code = (quey! as NSString).substringFromIndex(codeString.characters.count)
//        HMPrint(code)
                /**
                 *  定义一个闭包
                 */
               HMUserAccountViewModel.shareInstance.loadAccessToken(code, loadAcceseeTokenCallback: { (error) in
                if error != nil{
                    HMPrint("加载出错了:\(error)")
                    SVProgressHUD.showErrorWithStatus("网路不给力")
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), {
                        self.close()
                    })

                    return;
                }
                 HMPrint("加载成功了")
                self.close()
                let controller = HMWelecomeController()
                
                //拿到代理对象
                (UIApplication.sharedApplication().delegate as!AppDelegate).switchViewController(controller)
                
               })
                }else{
        
        close()
        }
        
        return false
        }}
    /**
     获取accesstoken
     */
//    private func loadAccessToken(code: String){
//        let parameters = [
//            "client_id":client_id,
//             "client_secret":client_secret,
//             "grant_type":authorization_code,
//             "code":code,
//             "redirect_uri":redirect_uri
//    ]
//        
//        //发送请求
//        HMNetworkTool.sharedInstanse.POST(accessTokenString, parameters: parameters, progress: nil, success: { (task, responseObject) in
//            HMPrint("accessToken返回成功:\(responseObject)")
//            //将responseObject转化为模型
//            let result = responseObject as? [String:AnyObject]
//            //字典转模型
//           
//           
//            //绑定
//            if let dict = result {
//            let userAccount =  HMUserAccount.init(dict: dict)
//            
////                HMPrint("转模型成功: \(userAccount)")
//                
//                //路径
//                let filePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/account.plist")
//                
//                //归档
//                NSKeyedArchiver.archiveRootObject(userAccount, toFile: filePath!)
//                
//                HMPrint("地址是:\(filePath)")
//            }
//            
//            }) { (task, error) in
//                HMPrint("accessToken返回失败:\(error)")
//        }
//    
//    }
    
    
    func webViewDidFinishLoad(webView: UIWebView) {
        
        
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        HMPrint(error)
        
        if error?.code == 102 {
            return
        }
        
        
        
        SVProgressHUD.showErrorWithStatus("加载失败")
    }

}








